// -*- c++ -*-
//
//  File:         objfunc.cpp
//
//  Description:  Contains the objective function.
//                Change this for different problems.
//
//  Author:       Fernando Lobo
//
//  Date:         June/1999
//
//  Modified to be compliant with gcc 3.4 by Kumara Sastry
//  Date:        March/2006

#include "objfunc.hpp"
#include "chromosome.hpp"
#include "parameter.hpp"

#include <stdio.h>


double objfunc( chromosome &x,Validator * val )
{
   //
   // convert chromosome to a charater string
   //
   char *str = new char [ x.length() ];
   x.asString( str );
       
   //
   // call objective function
   //    
   double v = objective_func( str, x.length(),val );
   delete [] str;
   return v;
}

//------------------------------------------------------------


// unitation function. return the number of 1's
int unitation( char *chrom, int startBit, int endBit )
{
  int ones = 0;
  for( int i=startBit; i<= endBit; i++ )
    if( chrom[i] == '1' ) ones++;
  return ones;
}

//
// trap function described in Harik's Illigal Report No. 99010
// The global optimum is at 0000 and has fitness k+1.
// The local (deceptive) optima is at 1111 and has fitness k.
//
double trap( int k, int ones )
{
  if( ones == 0 ) return k+1;
  else return ones;
}


//
// Objective function.
// Change this function to try different problems
//
double objective_func( char *chrom, int lchrom,Validator * val ) throw(EHW_Exception)
{/*
  const int m = 10;
  const int k = 4;

  // sum a bunch of functions
  double accum = 0.0;
  for( int i=0; i< m; i++ )
    {
      int startBit = i*k;
      int endBit = startBit + k - 1;
      int ones = unitation( chrom, startBit, endBit );
      accum += trap( k, ones );
    }
	  return accum;

	*/
	
	if (lchrom != 1024)	
		{
		printf("[ERROR] ECGA:objfunc - Num ob bits mismatch\n");
		return 0;
		}
	//ELSE translation
	int i,j,p;
	int array[DEF_COLS][DEF_ROWS][LUT_SIZE];
	for(i=0;i< DEF_COLS;i++)
		{
		for(j=0;j<DEF_ROWS;j++)
			{
			for(p=0;p<LUT_SIZE;p++)
				{
				char buff = chrom[p+LUT_SIZE*j+DEF_ROWS*i];
				array[i][j][p]=atoi(&buff);
				}
			}
		}
	
	Individuo *In[1];
	In[0] = new Individuo();
	//assign DNA from array
	In[0]->arrayInit(array);
	//Individuo **I=I;
	Popolazione *P= new Popolazione(1);
	P->load_list(1,In);
	unsigned int value_max=val->getMaxScore();
	unsigned int value=val->valuta_pop(P);
	//In[0]->print_geno();
	//printf("[INFO] ECGAobjfunction: Fitness= %u Max=%u \n", value,value_max);
	/*if(value_max=value)
		{
		throw EHW_Exception(chrom);
		}*/
	return (int)In[0]->fitness;
	
}








